package com.xc.app.controller;

import com.xc.app.domain.User;
import com.xc.app.repositorys.UserRepository;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping
public class TestController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private UserRepository userRepository;
    @RequestMapping("noLogin")
    public Object noLogin(){
        return new HashMap<String, Object>() {
            {
                this.put("code", 1);
                this.put("msg", "no login");
            }
        };
    }

    @RequestMapping("login")
    public Object login(String username, String password) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(usernamePasswordToken);   //完成登录
        User user = (User) subject.getPrincipal();
        log.info("login username:[{}]", user.getLoginName());
        return new HashMap<String, Object>() {
            {
                this.put("code", 0);
                this.put("msg", "success");
            }
        };
    }

    @RequestMapping("index")
    public Object index() {
        return new HashMap<String, Object>() {
            {
                this.put("code", 0);
                this.put("msg", "index");
            }
        };
    }

    @RequestMapping("refuse")
    public Object refuse() {
        return new HashMap<String, Object>() {
            {
                this.put("code", 1);
                this.put("msg", "权限不足");
            }
        };
    }

    @RequestMapping("get/{id}")
    public User findOne(@PathVariable Long id) {
        return userRepository.findOne(id);
    }
}
